import React from "react";
import "./CanvasLib.less";

export default class Home extends React.Component {
  state = {
    avgBGC: "blue",
  };
  componentDidMount() {
    this.getColor();
  }
  getColor = () => {
    var imgSrc =
      "https://hsrj.obs.cn-south-1.myhuaweicloud.com/underline/zhiyou-miniprogram/goods_details.png";
    const imgEle = document.createElement("img");
    const canvas = document.createElement("canvas");
    imgEle.src = imgSrc;
    imgEle.crossOrigin = "Anonymous";
    imgEle.onload = () => {
      var ctx = canvas.getContext("2d");
      var naturalImgSize = [imgEle.naturalWidth, imgEle.naturalHeight];
      canvas.width = naturalImgSize[0];
      canvas.height = naturalImgSize[1];

      //绘制到canvas
      ctx.drawImage(imgEle, 0, 0);
      //获取imageData：rgba像素点，每个像素点由rgba 4个数据表示
      var imgData = ctx.getImageData(0, 0, canvas.width, canvas.height);
      const leftSectionData = [];
      const rightSectionData = [];
      // 第一行像素点，数据个数
      const oneLineImgDataLen = canvas.width * 4;

      console.log("canvas---", canvas);
      console.log("imgData---", imgData);
      console.log("imgData.data.length---", imgData.data.length);
      console.log("oneLineImgDataLen---", oneLineImgDataLen);

      imgData.data.forEach((colorVal, i) => {
        // 取左右像素区域的比例，左边20% 右边20%
        if (
          i % oneLineImgDataLen < 0.2 * oneLineImgDataLen ||
          i % oneLineImgDataLen >= 0.8 * oneLineImgDataLen
        ) {
          const inLeft = i % oneLineImgDataLen <= 0.5 * oneLineImgDataLen;
          if (i % 4 === 0) {
            // 获取rgb均值
            const curAverageRGB =
              (imgData.data[i] + imgData.data[i + 1] + imgData.data[i + 2]) / 3;
            let leftOrRightRef = inLeft ? leftSectionData : rightSectionData;
            //每个像素数组里存四个值：本颜色值中的r、g、b的均值，以及r、g、b三个值。
            leftOrRightRef[leftOrRightRef.length] = [
              curAverageRGB,
              imgData.data[i],
              imgData.data[i + 1],
              imgData.data[i + 2],
            ];
          }
        }
      });
      //根据数组里每个像素的rgb均值，计算出数组的所有象属的rgb均值
      const averageOfLeft = Math.round(
        leftSectionData.reduce((_cur, item) => {
          return _cur + item[0];
        }, 0) / leftSectionData.length
      );
      const averageOfRight = Math.round(
        rightSectionData.reduce((_cur, item) => {
          return _cur + item[0];
        }, 0) / rightSectionData.length
      );
      //find the most near color
      const findNearestIndex = (averageVal, arrBox) => {
        let _gapValue = Math.abs(averageVal - arrBox[0]);
        let _nearColorIndex = 0;
        arrBox.forEach((item, index) => {
          const curGapValue = Math.abs(item - averageVal);
          if (curGapValue < _gapValue) {
            _gapValue = curGapValue;
            _nearColorIndex = index;
          }
        });
        return _nearColorIndex;
      };

      const leftNearestColor =
        leftSectionData[findNearestIndex(averageOfLeft, leftSectionData)];
      const rightNearestColor =
        rightSectionData[findNearestIndex(averageOfRight, rightSectionData)];
      console.log(leftNearestColor, rightNearestColor);
      this.setState({
        avgBGC: `linear-gradient(90deg,rgba(${leftNearestColor[1]},${leftNearestColor[2]},${leftNearestColor[3]},1) 0%,rgba(${rightNearestColor[1]},${rightNearestColor[2]},${rightNearestColor[3]},1) 100%`,
      });
    };
  };

  render() {
    const { avgBGC } = this.state;
    return <div className="canvasLibWrap" style={{ background: avgBGC }}></div>;
  }
}
